package protocol.SZ_2021;

import utils.HexUtils;

import java.nio.charset.Charset;

/**
 * 深圳市地方标准
 * DB4403/T 187—2021
 * 代替：SZDB/Z 65—2012
 */
public class SZ_2021Cmd {

    private byte[] cmd;
    private int index = 13;

    public SZ_2021Cmd(byte[] cmd){
        this.cmd = cmd;
    }

    public void resetIndex(){
        index = 13;
    }

    /**
     * 获取命令字
     * @return
     */
    public String readOrder(){
        return HexUtils.toHex(cmd[1],1);
    }
    public byte order(){
        return cmd[1];
    }

    public String readSubOrder(){
        return HexUtils.toHex(cmd[2],1);
    }
    public byte subOrder(){
        return cmd[2];
    }

    public void moveIndex(int len){
        index += len;
    }

    public int readWord(){
        return readInt(2);
    }

    public int readDWord(){
        return readInt(4);
    }

    public int readInt(int len){
        if (len > 4){
            //int类型最多占4个字节
            return -1;
        }
        int num = 0;
        for (int i= 0;i<len;i++){
            num = num << 8;
            num = num |(cmd[index+i] &0xFF);
        }
        index += len;
        return num;
    }

    public String readString(int len){
        return readString(len,Charset.forName("GBK"));
    }

    /**
     * 获取字符串
     * @param len 如果为-1，则持续读到0x00判定结束
     * @param charset
     * @return
     */
    public String readString(int len, Charset charset){

        if (len < 0){
            for (int i = 0;i< cmd.length;i++){
                if (cmd[index+i] == 0x00){
                    len = i+1;
                    break;
                }
            }
        }

        byte[] data = new byte[len];
        System.arraycopy(cmd,index,data,0,len);
        index += len;
        return new String(data,charset);
    }

    public String readBCD(int len){
        byte[] data = new byte[len];
        System.arraycopy(cmd,index,data,0,len);
        index+= len;
        return HexUtils.toHexStr(data);
    }

    /**
     * 剩余可读内容大小
     * @return
     */
    public int leftSize(){
        return cmd.length - index -2;
    }

    public String seq(){
        return HexUtils.toHexStr(new byte[]{cmd[11],cmd[12]});
    }

    public int readInt() {
        return readInt(1);
    }
}
